package com.ryit.im.controller;

import com.ryit.im.pojo.base.Result;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传
 */
@RequestMapping("file")
@RestController
public class FileController {


    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws IOException {
        String path = ClassUtils.getDefaultClassLoader().getResource("static/upload").getPath();
        String returnUrl = req.getScheme() + "://" + req.getServerName() + req.getContextPath() + "/static/upload/";
        //图片访问的URI
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 判断上传的文件是否为空
        boolean isEmpty = file.isEmpty();
        if (isEmpty) {
            return Result.error("上传失败!,上传的文件为空");
        }

        // 检查文件大小
        long fileSize = file.getSize();
        if (fileSize > 50  * 1024*1024) {
            return Result.error("只能发送50M以内的文件");
        }




        try {
            String originalFilename = file.getOriginalFilename();
            // 确定最终保存时使用的文件
            String fileName  = UUID.randomUUID().toString();
            String suffix = "";
            int beginIndex = originalFilename.lastIndexOf(".");
            if (beginIndex != -1) {
                suffix = originalFilename.substring(beginIndex);
            }
            // 执行保存文件
            File dest = new File(path, fileName + suffix);
            file.transferTo(dest);
            return Result.success().put("fileName",fileName).put("data",returnUrl + fileName+ suffix);
            //告诉页面上传成功了
        } catch (IOException e) {
            e.printStackTrace();
            //出现异常，则告诉页面失败
        }
        return Result.error("上传失败");
    }


}
